package fueltrack.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import fueltrack.client.FuelTrackDataService;
import fueltrack.client.FuelTrackEntry;

public class FuelTrackDataServiceImpl extends RemoteServiceServlet implements FuelTrackDataService {

	private static final long serialVersionUID = -5924427325715627448L;

	private DatastoreService datastoreService;
	private List<FuelTrackEntry> entries;
	
	public FuelTrackDataServiceImpl() {
		datastoreService = DatastoreServiceFactory.getDatastoreService();
		
		loadEntriesFromDataStore();
		
//		entries.add(new FuelTrackEntry("New Zealand", "Air New Zealand", "AIRNZ", 12.87453, -0.1436573578, new Date()));
//		entries.add(new FuelTrackEntry("New Zealand", "Sheep Industries", "BAHHH", 12.87453, -0.1436573578, new Date()));
//		entries.add(new FuelTrackEntry("Australia", "Endeavour Energy", "EENGY", 12.87453, -0.1436573578, new Date()));
//		entries.add(new FuelTrackEntry("Australia", "Ausgrid", "ASGRD", 12.87453, -0.1436573578, new Date()));
//		entries.add(new FuelTrackEntry("America", "Dept of Education", "DPEDU", 12.87453, -0.1436573578, new Date()));
	}

	@Override
	public List<FuelTrackEntry> getFuelTrackEntries(boolean force) {
		if (force)
			loadEntriesFromDataStore();
		
		return entries;
	}

	@Override
	public void addFuelTrackEntry(FuelTrackEntry entry) {
		Entity entity = new Entity(FuelTrackEntry.class.getSimpleName(), entry.getDate().toString());
		
		entity.setProperty("date", entry.getDate());
		entity.setProperty("odometer", entry.getOdometer());
		entity.setProperty("tripMeter", entry.getTripMeter());
		entity.setProperty("litres", entry.getLitres());
		entity.setProperty("amount", entry.getAmount());
		
		datastoreService.put(entity);
		
		entries.add(entry);
	}
	
	private void loadEntriesFromDataStore() {
		entries = new ArrayList<FuelTrackEntry>();
		
		PreparedQuery query = datastoreService.prepare(new Query(FuelTrackEntry.class.getSimpleName()).addSort("date"));
		for (Entity entity : query.asIterable()) {
			FuelTrackEntry entry = new FuelTrackEntry();
			
			entry.setDate((Date) entity.getProperty("date"));
			entry.setOdometer((Long) entity.getProperty("odometer"));
			entry.setTripMeter((Double) entity.getProperty("tripMeter"));
			entry.setLitres((Double) entity.getProperty("litres"));
			entry.setAmount((Double) entity.getProperty("amount"));
			
			entries.add(entry);
		}
	}
}
